'use strict';

const {
	FILE
} = require("dns");

const db = uniCloud.database()
exports.main = async (event, context) => {
	const {
		userId,
		filePath
	} = event;
	const userInfo = await db.collection('user').doc(userId).get()
	const oldUrl = userInfo.data[0].avatar;
	//删除旧的
	try {
		await uniCloud.deleteFile({
			fileList: [oldUrl]
		})
	} catch (e) {
		console.log(e)
	};
	//更新用户头像
	await db.collection('user').doc(userId).update({
		avatar: filePath
	});
	const id = userInfo.data[0].id;
	await db.collection('article').where({
		'author.id': id
	}).update({
		'author.avator': filePath
	});

	return {
		code: 0,
		data: {
			msg: '修改头像成功'
		}
	}
};